package cn.echisan.homework.interceptor;

import cn.echisan.homework.annotation.HasAnyRoles;
import cn.echisan.homework.enums.Role;
import cn.echisan.homework.model.User;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by echisan on 2018/5/30
 */
public class HasAnyRolesInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod handlerMethod = null;
        if (handler instanceof HandlerMethod){
            handlerMethod = (HandlerMethod) handler;
        }else {
            return true;
        }

        Method method = handlerMethod.getMethod();
        HasAnyRoles hasAnyRoles = method.getAnnotation(HasAnyRoles.class);
        if (hasAnyRoles == null){
            return true;
        }

        if (hasAnyRoles.value().length != 0){
            Role[] roles = hasAnyRoles.value();
            User user = (User) request.getSession().getAttribute("user");
            for (Role role : roles){
                if (user.getRole().equals(role.name())){
                    return true;
                }
            }
        }

        request.setAttribute("msg","你没有该权限");
        request.getRequestDispatcher("/error").forward(request,response);
        return false;
    }
}
